<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use lijieying\Wechat\WechatOpenid;

class LoginController extends Controller
{

    public function wechatLogin(Request $request)
    {
        $code = $request->input('code');
        $res = json_decode(WechatOpenid::getOpenid($code), true);
        if (isset($res['errcode'])) return ['code' => 500, 'msg' => '请求出错', 'data' => ''];
        $openid = $res['openid'];
        $dataUser = DB::table('pet_user')->where('openid', '=', $openid)->select('user_id','headimgurl','nickname')->get();
        $checkUser = count($dataUser);
//            已有账号直接返回信息
        if ($checkUser) return ['code' => 200, 'msg' => '登录成功', 'data' => $dataUser[0]];
//            没有账号则插入数据
        $userInfo = json_decode($request->input('userInfo'),true);
        $addUser = DB::table('pet_user')->insert(
            ['openid'=>$openid,'nickname'=>$userInfo['nickName'],'headimgurl'=>$userInfo['avatarUrl'],'created_at'=>date("Y-m-d h:i:s")]
        );
        if ($addUser) return ['code' => 200, 'msg' => '注册成功', 'data' => $userInfo];
        return ['code' => 500, 'msg' => '请求出错', 'data' => ''];
    }

    /**
     * 通过code获取session_key和openid
     * @param Request $request
     * @return bool|string
     */
    public function getOpenId($code)
    {
        $code1 = $code;
        return WechatOpenid::getOpenid($code1);
    }
}
